import pygame

import Musics
import Players
import Sprite_Group
import Walls
import Enemies

from Map_Data import maps
from Config import TLSIZE, WIDTH, HEIGHT, FPS, GAMEBACKGROUND, FIGHTBGM, MAXMAP, DEADPAGE, FONT
import Config
import Buttons

pygame.init()
# 初始化 Mixer
pygame.mixer.init()
# 设置音量
volume = 0.5  # 50% 音量
pygame.mixer.music.set_volume(volume)

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('黑暗地牢')
clock = pygame.time.Clock()

music = Musics.Music(FIGHTBGM)
music.play(-1)

running = True

class Game:
    def __init__(self):
        self.now_lv = 0
        self.preparing = False  # 新增：准备状态
        self.prepare_start_time = 0  # 准备开始时间
        self.prepare_duration = 4000  # 准备持续时间（毫秒）
        self.font = pygame.font.Font(FONT, 74)  # 创建字体对象
        self.bulletsflag = False

    def all_update(self,keys, mouse):
        Sprite_Group.Player_group.update(keys, mouse)
        Sprite_Group.Enemy_group.update()
        if  self.bulletsflag:
            Sprite_Group.Player_Bullet_group.update()
            Sprite_Group.Enemy_Bullet_group.update()
        else :
            Sprite_Group.Player_Bullet_group.empty()
            Sprite_Group.Enemy_Bullet_group.empty()
        Sprite_Group.Explode_group.update()
        Sprite_Group.Wall_group.update()
        Sprite_Group.StatusBar_grop.update()

    @staticmethod
    def check_live():
        for t in Sprite_Group.Player_group:
            if not t.live:
                Sprite_Group.Player_group.remove(t)

        for t in Sprite_Group.Enemy_group:
            if not t.live:
                Sprite_Group.Enemy_group.remove(t)

        for t in Sprite_Group.Player_Bullet_group:
            if not t.live:
                Sprite_Group.Player_Bullet_group.remove(t)

        for t in Sprite_Group.Enemy_Bullet_group:
            if not t.live:
                Sprite_Group.Enemy_Bullet_group.remove(t)

        for t in Sprite_Group.Explode_group:
            if not t.live:
                Sprite_Group.Explode_group.remove(t)

        for t in Sprite_Group.Wall_group:
            if not t.live:
                Sprite_Group.Wall_group.remove(t)

        for t in Sprite_Group.StatusBar_grop:
            if not t.live:
                Sprite_Group.StatusBar_grop.remove(t)

    def all_blit(self,surface):
        Sprite_Group.Player_group.draw(surface)
        Sprite_Group.Enemy_group.draw(surface)
        if self.bulletsflag:
            Sprite_Group.Player_Bullet_group.draw(surface)
            Sprite_Group.Enemy_Bullet_group.draw(surface)
        Sprite_Group.Explode_group.draw(surface)
        Sprite_Group.Wall_group.draw(surface)
        Sprite_Group.StatusBar_grop.draw(surface)

    def create_map(self):
        for y, row in enumerate(maps[self.now_lv]):
            for x, cell in enumerate(row):
                if cell == 'p1':
                    if self.now_lv==0 :
                        p1 = Players.Player1(x * TLSIZE, y * TLSIZE)
                        Sprite_Group.Player_group.add(p1)
                    else :
                        for player in Sprite_Group.Player_group:
                            if player.name == "Player1":
                                player.rect.x = x * TLSIZE
                                player.rect.y = y * TLSIZE

                elif cell == 'p2' and Config.get_pairmode():
                    if  self.now_lv==0:
                        p2 = Players.Player2(x * TLSIZE, y * TLSIZE)
                        Sprite_Group.Player_group.add(p2)
                    else :
                        for player in Sprite_Group.Player_group:
                            if player.name == "Player2":
                                player.rect.x = x * TLSIZE
                                player.rect.y = y * TLSIZE

                elif cell == 'w':

                    w=Walls.Wall(x*TLSIZE,y*TLSIZE)
                    Sprite_Group.Wall_group.add(w)

                elif cell[0]== 'e':
                    lv = int(cell[1])
                    e=Enemies.Enemy(x*TLSIZE,y*TLSIZE,lv)
                    Sprite_Group.Enemy_group.add(e)

        self.preparing = True  # 地图创建后设置准备状态
        self.prepare_start_time = pygame.time.get_ticks()

    def next_lv(self):
        if len(Sprite_Group.Enemy_group) == 0 and self.now_lv <= MAXMAP:
            Sprite_Group.Wall_group.empty()
            Sprite_Group.Explode_group.empty()
            Sprite_Group.Enemy_Bullet_group.empty()
            Sprite_Group.Player_Bullet_group.empty()
            self.create_map()
            self.now_lv += 1

    def draw(self,surface):

        self.all_blit(surface)

        if self.preparing:
            self.bulletsflag = False# 如果正处于准备状态
            elapsed_time = (pygame.time.get_ticks() - self.prepare_start_time) / 1000.0
            remaining_time = max(0, int((self.prepare_duration / 1000.0) - elapsed_time))

            # 显示当前关卡信息
            level_text = self.font.render(f'Level {self.now_lv}', True, (0, 0,0))
            level_rect = level_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 100))
            surface.blit(level_text, level_rect)

            # 显示倒计时
            if remaining_time > 0:
                count_text = self.font.render(str(remaining_time), True, (0, 0, 0))
                count_rect = count_text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
                surface.blit(count_text, count_rect)
            else:
                self.preparing = False
                self.bulletsflag = True # 倒计时结束后取消准备状态

    def update(self, k_e, m_e):
        if not self.preparing:
            # 只有不在准备状态时才更新精灵
            self.next_lv()
            self.check_live()
            self.all_update(k_e, m_e)

    def change_page(self, all_e):
        if len(Sprite_Group.Player_group) <=0 :return Dead()
        return self

class Home:

    def __init__(self):
        self.start_button = Buttons.Button(WIDTH//2-50,HEIGHT//2-25,100,50,"开始游戏",(255,255,255,0))
        self.quit_button = Buttons.Button(WIDTH//2-50,HEIGHT//2+100,100,50,"退出游戏",(0,0,255,0))
        self.setting_button = Buttons.Button(WIDTH // 2 - 50, HEIGHT // 2 + 50, 100, 50, "设置", (0, 0, 255, 0))

    def draw(self,surface):
        self.start_button.draw(surface)
        self.quit_button.draw(surface)
        self.setting_button.draw(surface)

    def to_game(self,all_e):
        for e in all_e:
            if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
                if self.start_button.is_clicked(e.pos):
                    return True
        return False

    def quit_game(self,all_e):
        global running
        for e in all_e:
            if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
                if self.quit_button.is_clicked(e.pos):
                    running=False

    def to_setting(self,all_e):
        for e in all_e:
            if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
                if self.setting_button.is_clicked(e.pos):
                    return True
        return False

    def update(self,k_e, m_e):
        pass

    def change_page(self,all_e):
        if self.to_game(all_e) :return Game()
        if self.quit_game(all_e):return self
        if self.to_setting(all_e):return setting_page
        return self

class Dead:
    def __init__(self):
        self.image = pygame.image.load(DEADPAGE)
        self.rect = self.image.get_rect()
        self.start_time = pygame.time.get_ticks()  # 记录当前时间
        self.duration = 4000  # 倒计时持续时间为2秒
        self.font = pygame.font.Font(FONT, 74)  # 创建字体对象，用于渲染文本

    def draw(self, surface):

        # 绘制死亡页面图像
        surface.blit(self.image, (WIDTH // 2 - self.rect.width // 2, HEIGHT // 2 - self.rect.height // 2))

        # 计算剩余时间（以秒为单位）
        elapsed_time = (pygame.time.get_ticks() - self.start_time) / 1000.0
        remaining_time = max(0, int((self.duration / 1000.0) - elapsed_time))

        # 如果剩余时间大于0，则绘制倒计时
        if remaining_time > 0:
            text = self.font.render(str(remaining_time), True, (0,0, 0))  # 渲染文本
            text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2 + self.rect.height // 2 + 50))
            surface.blit(text, text_rect)  # 绘制文本到屏幕上
    @staticmethod
    def all_empty():
        Sprite_Group.Player_group.empty()
        Sprite_Group.Enemy_group.empty()
        Sprite_Group.Player_Bullet_group.empty()
        Sprite_Group.Enemy_Bullet_group.empty()
        Sprite_Group.Explode_group.empty()
        Sprite_Group.Wall_group.empty()
        Sprite_Group.StatusBar_grop.empty()

    def update(self, k_e, m_e):
        pass

    def change_page(self, all_e):
        # 检查是否已经过了指定的持续时间
        if (pygame.time.get_ticks() - self.start_time) >= self.duration:
            self.all_empty()
            return Home()
        else:
            return self

class Setting:
    def __init__(self):
        self.pvp = Buttons.SwitchList(500,500,200,25,['开启','关闭'],"友军伤害")
        self.pairplay = Buttons.SwitchList(500, 550, 200, 25, ['开启', '关闭'], "双人模式")
        self.quit_button = Buttons.Button(WIDTH // 2 - 50, HEIGHT // 2 +100, 100, 25, "返回菜单", (0, 0, 255, 0))
    def draw(self,surface):
        self.pvp.draw(surface)
        self.quit_button.draw(surface)
        self.pairplay.draw(surface)
    def update(self,k_e, m_e):
        if self.pairplay.now == 0:Config.set_pairmode(True)
        else :
            Config.set_pairmode(False)
            self.pvp.now = 1
        if self.pvp.now==0:Config.set_pvp(True)
        else :Config.set_pvp(False)
    def to_home(self,all_e):
        for e in all_e:
            if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
                if self.quit_button.is_clicked(e.pos):
                    return True
        return False
    def change_page(self, all_e):
        for e in all_e:
            if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
                self.pvp.is_clicked(e.pos)
                self.pairplay.is_clicked(e.pos)
        if self.to_home(all_e):return Home()
        return self

setting_page = Setting()

current_screen = Home()

while running:

    events = pygame.event.get()

    screen.fill(GAMEBACKGROUND)

    current_screen = current_screen.change_page(events)

    # 处理事件
    keyboard_events = pygame.key.get_pressed()
    mouse_events = pygame.mouse.get_pressed()

    # 更新和绘制当前界面
    current_screen.draw(screen)
    current_screen.update(keyboard_events,mouse_events)

    # 刷新屏幕
    pygame.display.update()

    clock.tick(FPS)
    # 检查是否退出游戏
    for event in events:
        if event.type == pygame.QUIT:
            running = False
            break
